<?php

namespace  App\Http\Controllers\V1;


use App\Events\V1\KdUserRegEvent;
use App\Helpers\RestResponseFactory;
use App\Helpers\RestUtils;
use App\Helpers\Utils;
use App\Http\Controllers\Controller;
use App\Models\Factory\InviteFactory;
use App\Models\Factory\SmsFactory;
use App\Models\Factory\UserFactory;
use App\Models\Factory\UserStatusFactory;
use App\Models\Orm\Pay;
use App\Models\Orm\UserIncome;
use Illuminate\Http\Request;


/**
 * 快捷登录
 * Class QuickController
 * @package App\Http\Controllers\V1
 */
class QuickController extends  Controller
{

    /**
     * 注册
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        //接收参数
        $data = $request->input();

        //验证两次密码输入是否一致
        if($data['password'] != $data['repassword'])
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),20001,20001,RestUtils::getErrorMessage(20001));

        }

//        检查验证码是否正确
        $re = SmsFactory::getSmsRandomFromCache($data['phone'].'_code_kk');
        if (!($re == $data['code']))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(), RestUtils::getErrorMessage(1204), 1204);
        }

        //生成该用户的唯一标识token并保存到数据库
        $user = UserFactory::getUserByMobile($data['phone']);
        //插入到用户状态表一条数据
        if(empty($user))
        {
            return RestResponseFactory::ok(RestUtils::getStdObj(),'',1124, RestUtils::getErrorMessage(1124));

        }

        if($user->password){
            return RestResponseFactory::ok(RestUtils::getStdObj(),'',20000, RestUtils::getErrorMessage(20000));

        }


        //生成钱包地址
         $pay = Pay::where('type',4)->orderBy(\DB::raw('RAND()'))->first();
        $token['wallet'] = $pay->address;
        $token['key'] = md5("miyao".time().$user->id);

        $token['password'] = $data['password'];
        $token['tr_password'] = $data['tr_password'];
        $token['terminal'] = $data['terminal'];
        $token['total'] = UserIncome::REGISTER;

        //把用户的唯一标识保存到数据库内
        UserFactory::addUserTokenByMobile($data['phone'],$token);

        //更新用户的最后登录时间
        UserFactory::addUserLassTime($data['phone']);

        //插入邀请关系表
        InviteFactory::addInviteUser($user->id,0);


        //初始化收入表
        InviteFactory::initUserIncome($user->id);
        if($user->invite_user_id == 0){
            //监听注册,开始插入表中
            event(new KdUserRegEvent([$data]));
        }
        $info['invite_code'] = Utils::getInviteCode($user->id);

        if($data['terminal'] == 3){
            return RestResponseFactory::ok($info,200);

        }
        return RestResponseFactory::ok(RestUtils::getStdObj(),200);
    }
}
